from scipy import *
from numpy import power
from simu_common import Cbid, getPt, getRevenue, getStepRevenue

g_threshold = 0.0
g_arrival_rate = 5

rng_poisson = stats.poisson(g_arrival_rate)
rng_p = stats.uniform()
rng_s = stats.uniform()


def bids_key(bid):
    return bid.r
    
    
def getThreshold(bids, l):
    '''
        assuming that the bids are sorted in order by p*s
        take the lth highest as threshold
    '''
    length = len(bids)
    if l < length:
        return bids[l].r
    else:
        return 0.0;
    
def getSingleStepNum():
    '''
        get the arrival number for one step
        with random generator Poisson
    '''
    return rng_poisson.rvs()
    
def getPS():
    '''
        get one pair of iid P and iid S with 
        random generator Uniform(0,1)
    '''
    return rng_p.rvs(), rng_s.rvs()

def refresh_rngs():
    '''
        refresh the random generators
    '''
    global rng_poisson
    global rng_p
    global rng_s
    del rng_poisson
    del rng_p
    del rng_s
    rng_poisson = stats.poisson(g_arrival_rate)
    rng_p = stats.uniform()
    rng_s = stats.uniform()
        
def exp_Rrate1(k=10, T=50, l=0, tao=1.4):
    refresh_rngs()
    bids = []
    threshold = 0.0
    total_revenue = 0.0
    
    for i in xrange(0, T):
        arrival = getSingleStepNum()
        bids_modified = False
        for j in xrange(0, arrival):
            p, s = getPS()
            bid = Cbid(p, s)
            if bid.r >= threshold:
                bids.append(bid)
                bids_modified = True
                
        if bids_modified:        
            bids.sort(key=bids_key, reverse=True)

        if 0.0 == threshold:    
            threshold = getThreshold(bids, l)
            
        total_revenue = total_revenue + getStepRevenue(bids, k, tao)
        
    return total_revenue/T
    
def sample1(k=8):
    for i in xrange(0, k+5):
        r = 0.0
        t = 1000
        for j in xrange(0, t):
            r = r + exp_Rrate1(k=k, l=i)
        print i, r/t

if __name__ == "__main__":
    sample1()            
